package com.apes.fn.scm.settleCheck.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.retailOrder.repository.RetailOrderItemRepository;
import com.apes.fn.scm.retailOrder.repository.RetailOrderPayMethodRepository;
import com.apes.fn.scm.settleCheck.model.DynamicSummary;
import com.apes.fn.scm.settleCheck.reponsitory.DynamicSummaryRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 最原始版本的对账单服务类
 *
 * @BelongsProject: apes
 * @BelongsPackage: com.apes.fn.scm.settleCheck.service
 * @ClassName: RclService
 * @Author: pyb
 * @CreateTime: 2020-03-23 16:42
 * @Description: 对账单服务
 * @Version: 1.0
 */
@Deprecated
@Service("merchantReconciliationService")
public class MerchantReconciliationService extends DomainService {

    @Autowired
    private DynamicSummaryRepository dynamicSummaryRepository;
    @Autowired
    private EntityManager entityManager;


    /**
     * 支付方式明细
     *
     * @param request
     * @return
     */
    public Page<Map> findPaymentDetails(SimpleRequest request) {
        JSONObject model = checkRequest(request);
        String type_name = model.getString("paymentName");
        if (type_name.equals("其他应收-平台内-非集群车宝")) {
            Page<Map> result = SpringManager.getBean(RetailOrderPayMethodRepository.class).
                    findByPartnerIdAndType(
                            model.getJSONObject("fnCustomer").getString("id"),
                            model.getJSONObject("paymentType").getString("id"),
                            model.getDate("startDate"), model.getDate("endDate"), PageRequest.of((Integer.parseInt(request.get("page").toString())) - 1, request.get("size"))
                    );
            return result;
        } else if (type_name.equals("其他应收-平台外")) {
            Page<Map> result = SpringManager.getBean(RetailOrderPayMethodRepository.class).
                    findByPartnerIdAndTypeTwo(
                            model.getJSONObject("fnCustomer").getString("id"),
                            model.getJSONObject("paymentType").getString("id"),
                            model.getDate("startDate"), model.getDate("endDate"), PageRequest.of((Integer.parseInt(request.get("page").toString())) - 1, request.get("size"))
                    );
            return result;
        } else {
            Page<Map> result = SpringManager.getBean(RetailOrderPayMethodRepository.class).
                    findByPartnerIdAndTypeForJequn(
                            model.getJSONObject("fnCustomer").getString("id"),
                            model.getJSONObject("paymentType").getString("id"),
                            model.getDate("startDate"), model.getDate("endDate"), PageRequest.of((Integer.parseInt(request.get("page").toString())) - 1, request.get("size"))
                    );
            return result;
        }


    }

    /**
     * 业务明细
     *
     * @param request
     * @return
     */
    public Page<Map> findBusinessDetails(SimpleRequest request) {
        JSONObject model = checkRequest(request);
        String serveType = model.getString("serveType");

        Page<Map> result = SpringManager.getBean(RetailOrderItemRepository.class).
                findByCompanyIdAndServeTypeAndCreateDate(
                        model.getJSONObject("fnCustomer").getString("id"), serveType,
                        model.getDate("startDate"), model.getDate("endDate"),
                        PageRequest.of((Integer.parseInt(request.get("page").toString())) - 1, request.get("size"))
                );


        return result;
    }

    /**
     * 拼接表单
     *
     * @param request
     * @return
     */
    public Map<String, Object> getForm(SimpleRequest request) {
        JSONObject model = checkRequest(request);
        //获取动态配置表
        Optional<DynamicSummary> summary = null;
        if (model.getString(String.valueOf(model.getJSONObject("agentPaymentItem"))) == null && model.getString("description") != null) {
            summary = dynamicSummaryRepository.findOne(JpaDsl.toCriteriaByEq("description", model.getString("description")));
        } else {
            summary = dynamicSummaryRepository.findOne(JpaDsl.toCriteriaByEq("agentPaymentItem.id", model.getJSONObject("agentPaymentItem").get("id")));
        }

        DynamicSummary dynamicSummaries = summary.orElse(null);
        //取结果集
        String sql = " AND COMPANY_ID=:COMPANY_ID AND A.CREATE_DATE >= :startDate AND A.CREATE_DATE<= :endDate";
        Query query = entityManager.createNativeQuery(dynamicSummaries.getSqlInquiryHeaderName() + sql);
        query.setParameter("startDate", model.getDate("startDate"));
        query.setParameter("endDate", model.getDate("endDate"));
        query.setParameter("COMPANY_ID", model.getJSONObject("fnCustomer").getString("id"));
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        List<Map> resultList = query.getResultList();
        // 获取数据
        JSONArray footer = new JSONArray();
        return MapUtil.mapper(
                "content", resultList,
                "total", resultList.size(),
                "size", resultList.size(),
                "tableHeader", getTableHeader(resultList),
                "footer", footer
        );
    }

    /**
     * 拼接表头
     *
     * @param headers
     * @return
     */
    public List<Map> getTableHeader(List<Map> headers) {
        List<Map> temp = new ArrayList<>();
        Map map = headers.stream().findFirst().orElse(new HashMap());
        map.forEach((k, v) -> {
            temp.add(MapUtil.mapper(
                    "templateOptions", new HashMap(),
                    "expressionProperties", new HashMap(),
                    "hooks", new HashMap(),
                    "headerName", k,
                    "sum", k.toString().contains("SUM"),
                    "field", k,
                    "cellEditor", "input"
            ));
        });
        List<Map> headerName = temp.stream().sorted(Comparator.comparing(map1 -> map1.get("headerName").toString())).collect(Collectors.toList());
        for (Map header : headerName) {
            String name = header.get("headerName").toString().substring(1);
            header.put("headerName", name.replace("SUM", ""));
        }
        return headerName;
    }

    /**
     * 解析前端参数
     *
     * @param request
     * @return
     */
    public JSONObject checkRequest(SimpleRequest request) {
        JSONObject condition = request.get("condition");
        List<Map> filters = (List<Map>) condition.get("filters");
        JSONObject model = new JSONObject();
        filters.forEach(filter -> {
            model.put((String) filter.get("field"), filter.get("value"));
        });
        JSONObject groups = (JSONObject) condition.getJSONArray("groups").get(0);
        ((List<Map>) groups.get("filters")).forEach(filter -> {
            model.put((String) filter.get("field"), filter.get("value"));
        });
        return model;
    }


}
